from django.shortcuts import render, redirect, HttpResponse, reverse
from app_user.forms import RegisterForm, LoginForm
from lib.CommonResponse import CommonResponse
from app_user.models import UserInfo
from app_blog.models import Blog
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from lib.GenerateVerifyCode import create_verify_code


def register(request):
    register_form = RegisterForm()
    # 判断是否时post且时ajax传入的
    if request.method == 'POST' and request.is_ajax():
        kv_data = request.POST
        # 得到普通的键值对数据
        register_form = RegisterForm(kv_data)
        # 对数据进行清洗
        if not register_form.is_valid():
            # 如果有错误，将错误信息传回前端
            return CommonResponse(code=300, errors=register_form.errors)
        kv_data = register_form.cleaned_data
        # 获取到清洗过的数据
        # 并讲在数据库中没有的字段删除掉
        kv_data.pop('confirm_pwd')
        blog_title = kv_data.pop('blog_title')
        # 获取文件对象
        avatar_data = request.FILES.get('avatar')
        theme_data = request.FILES.get('theme')
        if not theme_data:
            blog_obj = Blog.objects.create(name=kv_data.get('username'), title=blog_title)
        else:
            blog_obj = Blog.objects.create(name=kv_data.get('username'), title=blog_title, theme=theme_data)
        # 创建用户，可以通过解包将字典中的键值对传回数据库
        if avatar_data:
            # 如何上传了头像，使用对应的头像
            user_obj = UserInfo.objects.create_user(**kv_data, blog=blog_obj, avatar=avatar_data)
        else:
            # 如果没有上传头像，使用默认头像
            user_obj = UserInfo.objects.create_user(**kv_data, blog=blog_obj)
        # 注册成功，向前端返回信息
        return CommonResponse(code=200, msg=f"{kv_data.get('username')} 注册成功")
    return render(request, 'register.html', locals())


#
# def login(request):
#     '''使用forms组件'''
#     if request.is_ajax() and request.method == 'POST':
#         data = request.POST
#         login_data = LoginForm(data)
#         # 获取输入的验证码
#         input_captcha = data.get('captcha')
#         # 从session会话中将正确的验证码拿回来
#         true_captcha = request.session.get('captcha')
#         if input_captcha.upper() != true_captcha.upper():
#             return CommonResponse(code=300, errors={'captcha': ['验证码输入错误']})
#         if not login_data.is_valid():
#             return CommonResponse(code=300, errors=login_data.errors)
#         username = login_data.cleaned_data.get('username')
#         password = login_data.cleaned_data.get('password')
#         user_obj = auth.authenticate(username=username, password=password)
#         if not user_obj:
#             return CommonResponse(code=300, errors={'password': ['用户名或密码错误']})
#         else:
#             auth.login(request=request, user=user_obj)
#             return CommonResponse(code=200, msg=f'用户{username}登录成功')
#
#     return render(request, 'login.html', locals())


def login(request):
    '''没用forms组件'''
    # login1_obj = LoginForm()
    if request.is_ajax() and request.method == 'POST':
        data = request.POST
        username = data.get('username')
        password = data.get('password')
        captcha = data.get('captcha')
        if captcha.upper() != request.session.get('captcha').upper():
            if captcha == '8888':
                # 万能验证码
                pass
            else:
                # return CommonResponse(code=200, msg=f'{username}登录成功')
                return CommonResponse(code=300, errors='验证码错误')
        user_obj = auth.authenticate(username=username, password=password)
        if not user_obj:
            return CommonResponse(code=300, errors='密码输入错误')
        auth.login(request, user_obj)
        return CommonResponse(code=200, msg=f'{username}登录成功')
    return render(request, 'Login_test.html', locals())


@login_required
def logout(request):
    auth.logout(request)
    url = reverse('home')
    return redirect(to=url)


def verify_code(request):
    captcha, img_data = create_verify_code()
    request.session['captcha'] = captcha
    return HttpResponse(img_data)


def editPassword(request):
    if request.is_ajax() and request.method == 'POST':
        data = request.POST
        # username = request.user.username
        # 获取数据
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        captcha = data.get('captcha')
        # 条件判断
        if not all([old_password, new_password, captcha]):
            return CommonResponse(code=100, errors='请补全参数')
        if captcha.upper() != request.session.get('captcha').upper():
            return CommonResponse(code=300, errors='验证码输入错误')
        is_pwd = request.user.check_password(old_password)
        if not is_pwd:
            return CommonResponse(code=400, errors='原密码输入错误')
        if len(new_password) < 5:
            return CommonResponse(code=401, errors='密码至少5位')
        # 保存修改数据
        request.user.set_password(new_password)
        request.user.save()
        # 将登录状态退出
        auth.logout(request)
        return CommonResponse(code=200, msg='密码修改成功')


@login_required
def editAvatar(request):
    if request.is_ajax() and request.method == 'POST':
        if request.session.get('captcha').upper() != request.POST.get('captcha').upper():
            return CommonResponse(code=300, errors='验证码错误')
        file_data = request.FILES.get('new_avatar')
        if not file_data:
            return CommonResponse(code=400, errors='没有指定修改头像')
        user_obj = request.user
        user_obj.avatar = file_data
        user_obj.save()
        return CommonResponse(msg='ok')
